package com.qingzhou.common.db.dao;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.qingzhou.common.web.domain.BaseEntity;
import com.qingzhou.common.web.domain.BaseEntityHasId;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.solon.annotation.Db;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Slf4j
public class AbstractSqlRepository<M extends BaseMapper<T>, T extends BaseEntity> implements Repository<T> {
    final static String START = "_start";
    final static String END = "_end";
    public T data;
    @Db
    protected M mapper;
    /**
     * 默认批次提交数量
     */
    int defaultBatchSize = 100;

    public M getMapper() {
        return mapper;
    }

    public int add(T entity) {
        Assert.notNull(entity);
        entity.setCreateTime(new Date());
        return mapper.insert(entity, true); //insertTemplate不会将null值的字段插入，数据库的默认值才会生效
    }

    public int update(T entity) {
        if (ObjectUtil.isNull(entity)) {
            return 0;
        }
        return mapper.update(entity, false); //upsert会将null值的字段插入，数据库默认值失效
    }

    public int addBatch(List<T> entities) {
        if (ObjectUtil.isNull(entities)) {
            return 0;
        }
        return mapper.insertBatch(entities);
    }

    public int delete(Serializable id) {
        return mapper.deleteById(id);
    }

    public Page<T> page(Integer pageNum, Integer pageSize, QueryWrapper query) {
        return mapper.paginate(pageNum, pageSize, query);
    }

    public Page<T> page(Integer pageNum, Integer pageSize) {
        return mapper.paginate(pageNum, pageSize,QueryWrapper.create());
    }

    public T getById(Serializable id){
        Assert.isTrue(ObjUtil.isNotNull(id),"请选择数据");
        return mapper.selectOneById(id);
    }

    public List<T> listByIds(List<Serializable> ids){
        return mapper.selectListByIds(ids);
    }
}